// JavaScript Document
/**
* 用于显示图片列表的ligerui组件
* 从ligerGrid修改而来
* 冀王历/2013-4-25
*/
(function ($)
{
	var l = $.ligerui;

	$.fn.ligerImageGrid = function (options)
	{
		return $.ligerui.run.call(this, "ligerImageGrid", arguments);
	};

	$.fn.ligerGetImageGridManager = function ()
	{
		return $.ligerui.run.call(this, "ligerGetImageGridManager", arguments);
	};

	$.ligerDefaults.ImageGrid = {
		width: 'auto', //宽度值
		height: 'auto', //宽度值
		
		imgWidth: 160,	//条目宽度
		imgHeight: 120, //条目高度
		spaceMargin: 10, //条目边距
		numsprerow: 0,//每行显示个数，等于0时自适应
		resizable: true, //table是否可伸缩
		url: false, //ajax url
		usePager: true, //是否分页
		page: 1, //默认当前页 
		pageSize: 15, //每页默认的结果数
		pageSizeOptions: [5, 10, 15, 20, 25], //可选择设定的每页结果数
		parms: [], //提交到服务器的参数
		dataType: 'server', //数据源：本地(local)或(server),本地是将读取p.data。不需要配置，取决于设置了data或是url
		dataAction: 'server', //提交数据的方式：本地(local)或(server),选择本地方式时将在客服端分页、排序。 
		newPageDataSource: 'server', //切换分页时的数据源
		dataPageAction: null, //分页模式：本地(local)或服务器(server),选择服务器方式时将不使用本地分页、排序。 
		checkbox: false, //是否显示复选框
		isScroll: true, //是否滚动
		onSuccess: null, //成功获取服务器数据的事件
		onBeforeCheckAll: null,//全选前事件，可以通过return false阻止操作(复选框)
		onCheckAll: null,//全选事件(复选框) 
		onBeforeCheck: null, //选择前事件，可以通过return false阻止操作(复选框)
		onCheck: null, //选择事件(复选框) 
		onBeforeShowData: null, //显示数据前事件，可以通过reutrn false阻止操作
		onAfterShowData: null, //显示完数据事件
		onError: null, //错误事件
		inWindow: true, //是否以窗口的高度为准 height设置为百分比时可用
		method: 'post', //提交方式
		async: true,
		root: 'rows', //数据源字段名
		record: 'total', //数据源记录数字段名
		dynamicHeader: 'cols',	//用于设置那些字段是有效的
		pageParmName: 'page', //页索引参数名，(提交给服务器)
		pagesizeParmName: 'pagesize', //页记录数参数名，(提交给服务器)
		sortnameParmName: 'sortname',  //页排序列名(提交给服务器)
        sortorderParmName: 'sortorder',  //页排序方向(提交给服务器) 
		onReload: null, //刷新事件，可以通过return false来阻止操作
		onToFirst: null, //第一页，可以通过return false来阻止操作
		onToPrev: null, //上一页，可以通过return false来阻止操作
		onToNext: null, //下一页，可以通过return false来阻止操作
		onToLast: null, //最后一页，可以通过return false来阻止操作
		mouseoverItemCssClass: 'l-imagegrid-item-over',
		delayLoad: false, //初始化时是否不加载
		onLoading: null, //加载时函数
		onLoaded: null, //加载完函数
		contentType: null, //Ajax contentType参数
		isChecked: null, //复选框 初始化函数
		imageRender: null,//自定义图片函数
		textRender: null,//自定义标题说明文字函数
		itemRender: null,//自定义条目渲染函数，用于个性化展示
		imageUrl: null,//图片url字段名或函数
		imageAlt: null,//图片说明字段名或函数
		imageTitle: null,//图片title属性字段或函数
		itemTitle: null, //条目标题字段或函数
		toolbar: null, //工具条,参数同 ligerToolbar的
		cache: false, //是否允许读取缓存
		checkbox:true,
		onClickImage: null,//图片点击事件
		onClickTitle: null, //标题点击事件
		showLoading: true,
		dynamicToolbar: false,		//使用动态工具条，工具条显示属性：fix|single|multi
        dynamicToolbarRender: null,	//使用自定义动态工具条处理程序
        operItem: null,		//是否添加操作项条目：{icon,title,click}
        operItemId: 'ig_last_oper_item', //操作项条目ID
        defaultIcon: null,
        errorIcon: null,
        emptyListText: '<h3>暂无数据...</h3>',
        //物联网定制功能，查找缩略图，如果不为空则将imageUrl转换格式后显示,转换方法：在文件名和扩展名之间插入标记 
        //如mini="-mini",imageUrl="pic.png",则转换后为pic-mini.png
        mini: null,
        itemState: false,//是否显示状态图标:true、false、gray
        itemStatePos:'RightBottom',//状态图标位置：LeftTop左上、RightTop右上、LeftBottom左下、RightBottom右下
        itemStateImg:'',//状态图标元素，为一个img标签,允许使用#{fieldName}引用字段值，或一个函数
        itemStateWidth: 16,
        itemStateHeight: 16,
        
        //自定义滚动条，使用jquery.nicescroll.js插件
        niceScroll: $.extend(true, {}, {
			    		enable: true,
			    		cursoropacitymin:0.5,
			    	    cursoropacitymax:0.8,
			    	    bouncescroll:false,
			    	    cursorcolor:'#999',
			    	    cursorwidth:"8px"
			    	}, $.qxNiceScrollOpts || {})
	
	
	};
	$.ligerDefaults.ImageGridString = {
		errorMessage: '发生错误',
		pageStatMessage: '显示从{from}到{to}，总 {total} 条 。每页显示：{pagesize}',
		pageTextMessage: 'Page',
		loadingMessage: '加载中...',
		noRecordMessage: '没有符合条件的记录存在'
	};
    //接口方法扩展
	$.ligerMethos.ImageGrid = $.ligerMethos.ImageGrid || {};
	$.ligerui.controls.ImageGrid = function (element, options)
	{
		$.ligerui.controls.ImageGrid.base.constructor.call(this, element, options);
	};

    $.ligerui.controls.ImageGrid.ligerExtend($.ligerui.core.UIComponent, {
        __getType: function ()
        {
            return '$.ligerui.controls.ImageGrid';
        },
        __idPrev: function ()
        {
            return 'imagegrid';
        },
        _extendMethods: function ()
        {
            return $.ligerMethos.ImageGrid;
        },
		_init: function ()
		{
			$.ligerui.controls.ImageGrid.base._init.call(this);
			var g = this, p = this.options;
			g.idfield = p.idfield;
			p.dataType = p.url ? "server" : "local";
			if (p.dataType == "local")
			{
				p.data = p.data || [];
				p.dataAction = "local";
			}
			if (p.isScroll == false)
			{
				p.height = 'auto';
			}
		},
		_render: function ()
		{
			var g = this, p = this.options;
			g.grid = $(g.element);
			g.grid.addClass("l-panel");
			var arr = [];
			arr.push("<div class='l-grid-loading'></div>");
			arr.push("<div class='l-panel-topbar' style='display:none'><div class='l-panel-topbarinner'></div></div><div class='l-clear'></div>");
			arr.push("<div class='l-panel-bwarp'>");
			arr.push("    <div class='l-panel-body'>");
			arr.push("        <div class='l-grid'>");
			arr.push("            <div class='l-grid2'>");
			arr.push("               <div class='l-grid-body l-grid-body2 l-scroll l-imagegrid-body'></div>");
			arr.push("            </div>");
			arr.push("        </div>");
			arr.push("    </div>");
			arr.push("</div>");
			arr.push("<div class='l-panel-bar'>");
			arr.push("    <div class='l-panel-bbar-inner'>");
			arr.push("        <div class='l-bar-group l-bar-message'><span class='l-bar-text'></span></div>");
			if(g.enabledCheckbox()){
				arr.push("        <div class='l-bar-group l-bar-checkall'><div class='l-grid-hd-cell-checkbox'><div class='l-grid-hd-cell-inner'><div class='l-grid-hd-cell-text l-grid-hd-cell-btn-checkbox'></div></div></div></div>");
				arr.push("        <div class='l-bar-group l-bar-checkall-text'>全选</div>");
				arr.push("        <div class='l-bar-separator'></div>");
			}
			arr.push("        <div class='l-bar-group l-bar-selectpagesize'></div>");
			arr.push("        <div class='l-bar-separator'></div>");
			arr.push("        <div class='l-bar-group'>");
			arr.push("            <div class='l-bar-button l-bar-btnfirst'><span></span></div>");
			arr.push("            <div class='l-bar-button l-bar-btnprev'><span></span></div>");
			arr.push("        </div>");
			arr.push("        <div class='l-bar-separator'></div>");
			arr.push("        <div class='l-bar-group'><span class='pcontrol'> <input type='text' size='4' value='1' style='width:50px' maxlength='8' /> / <span></span></span></div>");
			arr.push("        <div class='l-bar-separator'></div>");
			arr.push("        <div class='l-bar-group'>");
			arr.push("            <div class='l-bar-button l-bar-btnnext'><span></span></div>");
			arr.push("            <div class='l-bar-button l-bar-btnlast'><span></span></div>");
			arr.push("        </div>");
			arr.push("        <div class='l-bar-separator'></div>");
			arr.push("        <div class='l-bar-group'>");
			arr.push("             <div class='l-bar-button l-bar-btnload'><span></span></div>");
			arr.push("        </div>");
			arr.push("        <div class='l-bar-separator'></div>");
			arr.push("        <div class='l-clear'></div>");
			arr.push("    </div>");
			arr.push("</div>");
			g.grid.html(arr.join(''));
			//主体
			g.body = $(".l-panel-body:first", g.grid);
			//底部工具条         
			g.toolbar = $(".l-panel-bar:first", g.grid);
			//加载中
			g.gridloading = $(".l-grid-loading:first", g.grid);
			//顶部工具栏
			//g.topbar = $(".l-panel-topbar:first", g.grid);
			g.topbar = $(".l-panel-topbarinner:first", g.grid);
	
			g.gridview = $(".l-grid:first", g.grid);
			g.gridview.attr("id", g.id + "imagegrid");
			g.gridview2 = $(".l-grid2:first", g.gridview);
			//表主体     
			g.gridbody = $(".l-grid-body:first", g.gridview2);
	
			g.checkall = $(".l-bar-checkall", g.toolbar);
			
			g.currentData = null;
			g.cacheData = {}; //缓存数据
			
			var pc = $.extend({}, p);
			this._bulid();
			delete pc['data'];
			delete pc['url'];
			g.set(pc);
			if (!p.delayLoad)
			{
				if (p.url){
					g.set({ url: p.url });
				}else if (p.data){
					g.set({ data: p.data });
				}
			}
		},
		_setCssClass: function (value)
		{
			this.grid.addClass(value);
		},
		_setLoadingMessage: function (value)
		{
			this.gridloading.html(value);
		},
		_setToolbar: function (value)
        {
            var g = this, p = this.options;
            if (value && $.fn.ligerToolBar)
            {
                g.topbar.parent().show();
                g.toolbarManager = g.topbar.ligerToolBar(value);
                if (value.title)
                {
                    var jtitle = $("<div class='l-panel-topbartitle'><span>" + value.title + "</span></div>");
                    if (value.icon)
                    {
                        jtitle.append("<img class='l-panel-topbaricon' src='" + value.icon + "'></img>");
                        jtitle.addClass("l-panel-topbartitle-hasicon");
                    }
                    g.topbar.parent().append(jtitle);
                }
                if (p.toolbarShowInLeft)
                {
                    g.topbar.addClass("l-panel-topbarinner-left");
                }
            } else
            {
                g.topbar.parent().remove();
            }
        },
        isHorizontalScrollShowed: function ()
        {
            var g = this;
            var inner = g.gridbody.find(".l-grid-body-inner:first");
            if (!inner.length) return false;
            //20为横向滚动条的宽度
            return g.gridbody.width() - 20 < inner.width();
        },
		_setHeight: function (h)
		{
			var g = this, p = this.options;
			if (h == "auto"){return;}
			if (typeof h == "string" && h.indexOf('%') > 0){
				if (p.inWindow){
					h = $(window).height() * parseFloat(h) * 0.01;
				}else{
					h = g.grid.parent().height() * parseFloat(h) * 0.01;
				}
			}
			if (p.usePager) h -= 32;
			if (p.toolbar) h -= g.topbar.outerHeight();
			if (h > 0){
				g.gridbody.height(h);
				g.gridview.height(h);
			}
			g._updateHorizontalScrollStatus.ligerDefer(g, 10);
		},
		_updateHorizontalScrollStatus: function ()
        {
            var g = this, p = this.options;
            if (g.isHorizontalScrollShowed())
            {
                g.gridview.addClass("l-grid-hashorizontal");
            }
            else
            {
                g.gridview.removeClass("l-grid-hashorizontal");
            }
        },
        _setUrl: function (value)
		{
			this.options.url = value;
			if (value)
			{
				if(value=='#')return;
                this.options.dataType = "server";
                this.options.dataAction = "server";
				this.loadData(true);
			}
			else
			{
				this.options.dataType = "local";
                this.options.dataAction = "local";
			}
		},
		removeParm: function (name)
        {
            var g = this;
            var parms = g.get('parms');
            if (!parms) parms = {};
            if (parms instanceof Array)
            {
                removeArrItem(parms, function (p) { return p.name == name; });
            } else
            {
                delete parms[name];
            }
            g.set('parms', parms);
        },
        setParm: function (name, value)
        {
            var g = this;
            var parms = g.get('parms');
            if (!parms) parms = {};
            if (parms instanceof Array)
            {
                removeArrItem(parms, function (p) { return p.name == name; });
                parms.push({ name: name, value: value });
            } else
            {
                parms[name] = value;
            }
            g.set('parms', parms);
        },
		_setData: function (value)
		{
			this.loadData(this.options.data);
		},
		//刷新数据
		loadData: function (loadDataParm)
		{
			var g = this, p = this.options;
			g.loading = true;
			g.trigger('loadData');
			var clause = null;
			var loadServer = true;
			if (typeof (loadDataParm) == "function")
			{
				clause = loadDataParm;
				loadServer = false;
			}
			else if (typeof (loadDataParm) == "boolean")
			{
				loadServer = loadDataParm;
			}
			else if (typeof (loadDataParm) == "object" && loadDataParm)
			{
				loadServer = false;
				p.dataType = "local";
				p.data = loadDataParm;
			}
			//参数初始化
			if (!p.newPage) p.newPage = 1;
			var param = [];
			if (p.parms)
			{
				var parms = $.isFunction(p.parms) ? p.parms() : p.parms;
				if (parms.length)
				{
					$(parms).each(function ()
					{
						param.push({ name: this.name, value: this.value });
					});
				}
				else if (typeof parms == "object")
				{
					for (var name in parms)
					{
						param.push({ name: name, value: parms[name] });
					}
				}
			}
			if (p.dataAction == "server")
			{
				if (p.usePager)
				{
					param.push({ name: p.pageParmName, value: p.newPage });
					param.push({ name: p.pagesizeParmName, value: p.pageSize });
				}
				if (p.sortName)
                {
                    param.push({ name: p.sortnameParmName, value: p.sortName });
                    param.push({ name: p.sortorderParmName, value: p.sortOrder });
                }
			};
			$(".l-bar-btnload span", g.toolbar).addClass("l-disabled");
			if (p.dataType == "local")
			{
				g.filteredData = p.data || g.currentData;
				if (clause){
					g.filteredData[p.root] = g._searchData(g.filteredData[p.root], clause);
				}
				if (p.usePager){
					g.currentData = g._getCurrentPageData(g.filteredData);
				}else{
					g.currentData = g.filteredData;
				}
				g._showData();
			}
			else if (p.dataAction == "local" && !loadServer)
			{
				if (g.data && g.data[p.root])
				{
					g.filteredData = g.data;
					if (clause){
						g.filteredData[p.root] = g._searchData(g.filteredData[p.root], clause);
					}
					g.currentData = g._getCurrentPageData(g.filteredData);
					g._showData();
				}
			}
			else
			{
				g.loadServerData(param, clause);
			}
			g.loading = false;
		},
		loadServerData: function (param, clause)
		{
			var g = this, p = this.options;
			var ajaxOptions = {
				type: p.method,
				url: p.url,
				data: param,
				async: p.async,
				cache: p.cache,
				dataType: 'json',
				beforeSend: function ()
				{
					if (g.hasBind('loading'))
					{
						g.toggleLoading(true);
						g.trigger('loading');
					}
					else
					{
						g.toggleLoading(true);
					}
				},
				success: function (data)
				{
					if(g._destroyed===true){
						return;
					}
					if(typeof(data)=='string'){
						data = $.parseJSON(data);
					}
					g.trigger('success', [data, g]);
					if (!data || !data[p.root] || !data[p.root].length)
					{
						g.currentData = g.data = {};
						g.currentData[p.root] = g.data[p.root] = [];
						g.currentData[p.record] = g.data[p.record] = 0;
						g._showData();
						return;
					}
					
					g.data = data;
					//保存缓存数据-记录总数
                    if (g.data[p.record] != null && g.cacheData.records)
                    {
                        g.cacheData.records  = g.data[p.record];
                    }
					if (p.dataAction == "server")
					{
						g.currentData = g.data;
						//读取缓存数据-记录总数(当没有返回总记录数)
                        if (g.currentData[p.record] == null && g.cacheData.records)
                        {
                            g.currentData[p.record] = g.cacheData.records;
                        }
					}
					else
					{
						g.filteredData = g.data;
						if (clause){
							g.filteredData[p.root] = g._searchData(g.filteredData[p.root], clause);
						}
						if (p.usePager){
							g.currentData = g._getCurrentPageData(g.filteredData);
						}else{
							g.currentData = g.filteredData;
						}
					}
					g._showData.ligerDefer(g, 10, [g.currentData]);
				},
				complete: function ()
				{
					g.trigger('complete', [g]);
					if (g.hasBind('loaded'))
					{
						g.toggleLoading.ligerDefer(g, 10, [false]);
						g.trigger('loaded', [g]);
					}
					else
					{
						g.toggleLoading.ligerDefer(g, 10, [false]);
					}
				},
				error: function (XMLHttpRequest, textStatus, errorThrown)
				{
					g.currentData = g.data = {};
					g.currentData[p.root] = g.data[p.root] = [];
					g.currentData[p.record] = g.data[p.record] = 0;
					g.toggleLoading.ligerDefer(g, 10, [false]);
					$(".l-bar-btnload span", g.toolbar).removeClass("l-disabled");
					g.trigger('error', [XMLHttpRequest, textStatus, errorThrown]);
				}
			};
			if (p.contentType) ajaxOptions.contentType = p.contentType;
			$.ajax(ajaxOptions);
		},
		//获取属性值
		_getValueByName: function (data, name)
        {
            if(!data || !name)return null;
            if(name.indexOf('.') == -1)
            {
                return data[name];
            }
            else
            {
                try
                {
                    return new Function("data", "return data." + name + ";" )(data);
                }
                catch ( e )
                {
                    return null;
                }
            }
        },
		toggleLoading: function (show)
		{
			var g = this, p = this.options;
			g.gridloading[(show && p.showLoading) ? 'show' : 'hide']();
		},
		_setShowLoading: function (value)
        {
        	this.options.showLoading = value;
        },
        setHeight: function (h)
        {
            return this._setHeight(h);
        },
        //是否启用复选框列
        enabledCheckbox: function ()
        {
            return this.options.checkbox ? true : false;
        },
        _createRecordid: function ()
        {
            return "r" + (1000 + this.recordNumber);
        },
        _isRecordId: function (str)
        {
            return (str in this.records);
        },
		_getRecordDomId: function (itemdata)
        {
            return this.id + "|" + itemdata['__id'];
        },
		_addNewRecord: function (record)
        {
            var g = this, p = this.options;
			record['__index'] = g.recordNumber;
            g.recordNumber++;
            record['__id'] = g._createRecordid();
            g.items[record['__index']] = record;
            g.records[record['__id']] = record;
            return record;
        },
		_updateGridData: function ()
        {
            var g = this, p = this.options;
            g.recordNumber = 0;
            g.items = [];
            g.records = {};
			var data = g.currentData[p.root];
			if (data && data.length)
			{
				for (var i = 0; i < data.length; i++)
                {
                    var record = data[i];
                    g.formatRecord(record);
                    g._addNewRecord(record);
                }
			}
            return g.items;
        },
		//格式化数据
        formatRecord: function (record)
        {
            delete record['__id'];
            delete record['__index'];
            return record;
        },
        //改变分页
        changePage: function (ctype, npn)
        {
            var g = this, p = this.options;
            if (g.loading) return true;
            p.pageCount = parseInt($(".pcontrol span", g.toolbar).html());
            switch (ctype)
            {
                case 'first': if (p.page == 1) return; p.newPage = 1; break;
                case 'prev': if (p.page == 1) return; if (p.page > 1) p.newPage = parseInt(p.page) - 1; break;
                case 'next': if (p.page >= p.pageCount) return; p.newPage = parseInt(p.page) + 1; break;
                case 'last': if (p.page >= p.pageCount) return; p.newPage = p.pageCount; break;
                case 'input':
                    var nv = parseInt($('.pcontrol input', g.toolbar).val());
                    if (isNaN(nv)) nv = 1;
                    if (nv < 1) nv = 1;
                    else if (nv > p.pageCount) nv = p.pageCount;
                    $('.pcontrol input', g.toolbar).val(nv);
                    p.newPage = nv;
                    break;
            }
            if (p.newPage == p.page) return false;
            if (p.newPage == 1)
            {
                $(".l-bar-btnfirst span", g.toolbar).addClass("l-disabled");
                $(".l-bar-btnprev span", g.toolbar).addClass("l-disabled");
            }
            else
            {
                $(".l-bar-btnfirst span", g.toolbar).removeClass("l-disabled");
                $(".l-bar-btnprev span", g.toolbar).removeClass("l-disabled");
            }
            if (p.newPage == p.pageCount)
            {
                $(".l-bar-btnlast span", g.toolbar).addClass("l-disabled");
                $(".l-bar-btnnext span", g.toolbar).addClass("l-disabled");
            }
            else
            {
                $(".l-bar-btnlast span", g.toolbar).removeClass("l-disabled");
                $(".l-bar-btnnext span", g.toolbar).removeClass("l-disabled");
            }
            g.trigger('changePage', [p.newPage, ctype]);
            
            if(p.newPageDataSource == "server"){
            	p.dataAction = "server";
            	p.dataType = "server";
            }
            
            if (p.dataAction == "server")
            {
                g.loadData();
            }
            else
            {
                g.currentData = g._getCurrentPageData(g.filteredData);
                g._showData();
            }
        },
        getSelectedItems: function ()
        {
            var arr = [];
            for (var i in this.selected)
            {
                var o = this.selected[i];
                if (o['__id'] in this.records){
                    arr.push(o);
				}
            }
            return arr;
        },
        getSelectedItemObjs: function ()
        {
            var arr = [];
            for (var i in this.selected)
            {
                var o = this.selected[i];
                if (o['__id'] in this.records){
                    arr.push(this.getItemObj(o));
				}
            }
            return arr;
        },
        getItem: function (itemParm)
        {
            var g = this, p = this.options;
            if (itemParm == null) return null;
            if (typeof (itemParm) == "string")
            {
                if (g._isRecordId(itemParm)){
                    return g.records[itemParm];
				}else{
                    return g.items[parseInt(itemParm)];
				}
            }
            else if (typeof (itemParm) == "number")
            {
                return g.items[parseInt(itemParm)];
            }
            else if (typeof (itemParm) == "object" && itemParm.nodeType == 1 && !itemParm['__id']) //dom对象
            {
                return g._getItemByDomId(itemParm.id);
            }
            return itemParm;
        },
	   getItemObj: function (itemParm)
		{
			var g = this, p = this.options;
			if (itemParm == null) return null;
			if (typeof (itemParm) == "string")
			{
				if (g._isRecordId(itemParm)){
					return document.getElementById(g.id + "|" + itemParm);
				}else{
					return document.getElementById(g.id + "|" + g.items[parseInt(itemParm)]['__id']);
				}
			}
			else if (typeof (itemParm) == "number")
			{
				return document.getElementById(g.id + "|" + g.items[itemParm]['__id']);
			}
			else if (typeof (itemParm) == "object" && itemParm['__id']) //rowdata
			{
				return g.getItemObj(itemParm['__id']);
			}
			return itemParm;
		},
        _bulid: function ()
        {
            var g = this;
            g._clearGrid();
			//创建头部
            g._initBuildHeader();
            //宽度高度初始化
            g._initHeight();
            //创建底部工具条
            g._initFootbar();
            //创建分页
            g._buildPager();
            //创建事件
            g._setEvent();
        },
        _initBuildHeader: function ()
        {
            var g = this, p = this.options;
            if (p.toolbar)
            {
                if ($.fn.ligerToolBar){
                    g.toolbarManager = g.topbar.ligerToolBar(p.toolbar);
				}
            }
            else
            {
                g.topbar.remove();
            }
        },
        _initHeight: function ()
        {
            var g = this, p = this.options;
            if (p.height == 'auto')
            {
                g.gridbody.height('auto');
            }
            if (p.width)
            {
                g.grid.width(p.width);
            }
            g._onResize.call(g);
        },
		_initFootbar: function ()
		{
			var g = this, p = this.options;
			if (p.usePager)
			{
				//创建底部工具条 - 选择每页显示记录数
				var optStr = "";
				var selectedIndex = -1;
				$(p.pageSizeOptions).each(function (i, item)
				{
					if (p.pageSize == item){
						selectedIndex = i;
					}
					optStr += "<option value='" + item + "'>" + item + "</option>";
				});
				$('.l-bar-selectpagesize', g.toolbar).append("<select name='rp'>" + optStr + "</select>");
				g.pagesizeSelector = $('.l-bar-selectpagesize select', g.toolbar);
				if (selectedIndex != -1){
					g.pagesizeSelector[0].selectedIndex = selectedIndex;
				}
			}
			else
			{
				g.toolbar.hide();
			}
		},
		_searchData: function (data, clause)
		{
			var g = this, p = this.options;
			var newData = new Array();
			for (var i = 0; i < data.length; i++)
			{
				if (clause(data[i], i))
				{
					newData[newData.length] = data[i];
				}
			}
			return newData;
		},
        _clearGrid: function ()
        {
            var g = this, p = this.options;
            for (var i in g.items)
            {
                var itemobj = $(g.getItemObj(g.items[i]));
                itemobj.unbind();
            }
            //清空数据
           // g.gridbody.html("");
            g.gridbody.empty();
            g.recordNumber = 0;
            g.records = {};
            g.items = [];
            //清空选择的行
            g.selected = [];
            g.totalNumber = 0;
        },
        _fillGridBody: function (data)
        {
            var g = this, p = this.options;
            //加载数据 
            var arr = ['<div class="l-imagegrid-body-inner">'];
			if(data){
				if(p.numsprerow && p.numsprerow>0){
					var n = 0;
					for(var i=0; i<data.length; i++){
						var d = data[i];
						if(!d) continue;
						if(n%p.numsprerow==0){
							var ww = (p.imgWidth + p.spaceMargin*2 + 5)*p.numsprerow;
							arr.push('<div class="l-imagegrid-row" style="width:'+ww+'px">');
						}
						arr.push(g._getItemHtml(d));
						if((n+1)%p.numsprerow==0){
							arr.push('</div>');
						}
						n++;
					}
					if(p.operItem!=null){
						arr.push(g._getOperItemHtml());
						n++;
					}
					if(n%p.numsprerow!=0){
						arr.push('</div>');
					}
				}else{
					for(var i=0; i<data.length; i++){
						var d = data[i];
						if(!d) continue;
						arr.push(g._getItemHtml(d));
					}
					if(p.operItem!=null){
						arr.push(g._getOperItemHtml());
					}
				}
				
			}
			arr.push('</div>');
			
			var gridbodyHtml = $(arr.join(''));
			if(p.defaultIcon){
				$("img.l-imagegrid-img", gridbodyHtml).bind('error.layout2', function(){
					$(this).unbind('error.layout2');
					if($(this).attr('defimg')=='defimg'){
						if(p.errorIcon){
							if(p.errorIcon.indexOf('#')==-1){
								$(this).attr('src', p.errorIcon);
							}else{
								var record2 = g.getItem($(this).attr('itemid'));
								var iconurl2 = g._getIconUrl(record2, p.errorIcon);
								$(this).attr('src', iconurl2);
							}
						}
					}else{//defimg
						if(p.errorIcon){
							$(this).bind('error.layout2', function(){
								if(p.errorIcon.indexOf('#')==-1){
									$(this).attr('src', p.errorIcon);
								}else{
									var record2 = g.getItem($(this).attr('itemid'));
									var iconurl2 = g._getIconUrl(record2, p.errorIcon);
									$(this).attr('src', iconurl2);
								}
							});
						}
						if(typeof(p.defaultIcon) !== "function"){
							if(p.defaultIcon.indexOf('#')==-1){
								$(this).attr('src', p.defaultIcon);
							}else{
								var record = g.getItem($(this).attr('itemid'));
								var iconurl = g._getIconUrl(record, p.defaultIcon);
								$(this).attr('src', iconurl);
							}
						}else{
							if(p.defaultIconAjax){
								var record = g.getItem($(this).attr('itemid'));
								p.defaultIcon.call(g, record, $(this), function($img, imageurl){
									$img.attr('src', imageurl);
								});
							}else{
								var record = g.getItem($(this).attr('itemid'));
								$(this).attr('src', p.defaultIcon.call(g, record));
							}
						}
					}//defimg
				});
			}
			
			g.gridbody.empty().append(gridbodyHtml);
            g._gridBodyInner = $(".l-imagegrid-body-inner:first", g.gridbody);
			
			$("img.l-imagegrid-img", g._gridBodyInner).css({"width":p.imgWidth+"px", "height":p.imgHeight+"px"});
			
			var $rows = $('.l-imagegrid-row', g._gridBodyInner);
			if($rows.size()>0){
				g._gridBodyInner.width($rows.first().width());
			}
			
			//使用Ajax加载图片
			$("img[ajaxdefimg]", gridbodyHtml).each(function(){
				$(this).unbind('error.layout2');
				if(p.errorIcon){
					$(this).bind('error.layout2', function(){
						if(p.errorIcon.indexOf('#')==-1){
							$(this).attr('src', p.errorIcon);
						}else{
							var record2 = g.getItem($(this).attr('itemid'));
							var iconurl2 = g._getIconUrl(record2, p.errorIcon);
							$(this).attr('src', iconurl2);
						}
					});
				}
				var record = g.getItem($(this).attr('itemid'));
				p.defaultIcon.call(g, record, $(this), function($img, imageurl){
					$img.attr('src', imageurl);
				});
			});
			
			if(p.onClickImage){
				$("img.l-imagegrid-img", g._gridBodyInner).addClass("l-imagegrid-hand");
			}
			if(p.onClickTitle){
				$("div.l-imagegrid-title", g._gridBodyInner).addClass("l-imagegrid-hand");
				$("div.l-imagegrid-title", g._gridBodyInner).hover(function ()
				{
					$(this).addClass("l-imagegrid-title-over");
				}, function ()
				{
					$(this).removeClass("l-imagegrid-title-over");
				});
			}
			
			//无数据时
			if(g._gridBodyInner.html()=='' && p.emptyListText){
				g._gridBodyInner.html(p.emptyListText);
            }
			
            g._onResize();
        },
		
		_getItemHtml: function(d){
			var g = this, p = this.options;
			
			if(p.itemRender){//自定义条目渲染器
				var arr = [];
				arr.push('<div');//1
				arr.push(' id="' + g._getRecordDomId(d) + '"');
				arr.push(' class="l-imagegrid-item');
				if (g.enabledCheckbox() && p.isChecked && p.isChecked(d))
				{
					g.select(d, true, true);
					arr.push(' l-imagegrid-selected');
				}
				arr.push('">');
				
				var itemhtml = p.itemRender.call(g, d);
				arr.push(itemhtml);
				
				arr.push('</div>');//1
				
				return arr.join('');
			}
			
			var arr = [];
			arr.push('<div');//1
			arr.push(' id="' + g._getRecordDomId(d) + '"');
			arr.push(' class="l-imagegrid-item');
			if (g.enabledCheckbox() && p.isChecked && p.isChecked(d))
			{
				g.select(d, true, true);
				arr.push(' l-imagegrid-selected');
			}
			arr.push('">');
			//图片
			arr.push('<div');//2
			arr.push(' style="margin:'+p.spaceMargin+'px '+p.spaceMargin+'px 0 '+p.spaceMargin+'px;"');
			arr.push(' class="l-imagegrid-img-wrap');
			if(p.itemState === 'gray'){
				var _state = false;
				if(typeof(p.itemStateImg) == "function"){
					_state = p.itemStateImg.call(g, d);
				}else if(typeof(p.itemStateImg) == "string"){
					var fv = p.itemStateImg.split('=');
					if(typeof(d[fv[0]]) == "number"){
						_state = (d[fv[0]] == parseInt(fv[1]));
					}else{
						_state = ((''+d[fv[0]]) == fv[1]);
					}
				}
				if(_state){
					arr.push(' l-gray');
				}
			}
			arr.push('">');
			if(p.imageRender){
				var imghtml = p.imageRender.call(g, d);
				arr.push(imghtml);
			}else{
				arr.push('<img');
				arr.push(' class="l-imagegrid-img"');
				arr.push(' style="width:'+p.imgWidth+'px; height:'+p.imgHeight+'px;"');
				var src = "";
				if(typeof(p.imageUrl) == "function")
				{
					src = p.imageUrl.call(g, d);
				}
				else
				{
					src = g._getValueByName(d, p.imageUrl);
				}
				if(!(/\.\w+$/).test(src)){
					if(p.defaultIcon){
						if(typeof(p.defaultIcon) === "function"){
							if(p.defaultIconAjax){
								//Ajax加载默认图片
								if(p.errorIcon){ src = p.errorIcon;}
								arr.push(' ajaxdefimg="ajaxdefimg"');
							}else{
								src = p.defaultIcon.call(g, d);
							}
						}else{//默认图片
							if(p.defaultIcon.indexOf('#')==-1){
								src = p.defaultIcon;
							}else{
								src = g._getIconUrl(d, p.defaultIcon);
							}//默认图片
							arr.push(' defimg="defimg"');
						}
					}
				}else{
					if(p.mini){
						src = src.replace(/^(.+)(\.\w+)$/, '$1'+p.mini+'$2');
					}
				}
				
				arr.push(' src="'+src+'"');
				var alt = "";
				var tit = "";
				if(typeof(p.imageAlt) == "function"){
					alt = p.imageAlt.call(g, d);
				}else if(p.imageAlt){
					alt = g._getValueByName(d, p.imageAlt);
				}
				if(typeof(p.imageTitle) == "function"){
					tit = p.imageTitle.call(g, d);
				}else if(p.imageTitle){
					tit = g._getValueByName(d, p.imageTitle);
				}
				alt = alt || tit;
				tit = tit || alt;
				arr.push(' alt="'+alt+'"');
				arr.push(' title="'+tit+'"');
				arr.push(' itemid="'+d['__id']+'"');
				
				arr.push('/>');
			}
			arr.push('</div>');//2
			
			//文字和复选框
			arr.push('<div');//3
			arr.push(' class="l-imagegrid-title-wrap"');
			arr.push(' style="margin:6px '+p.spaceMargin+'px '+p.spaceMargin+'px '+p.spaceMargin+'px;width:'+p.imgWidth+'px"');
			arr.push('>');
			
			//复选框
			if(g.enabledCheckbox()){
				arr.push('<div class="l-imagegrid-checkbox-wrap">');
				arr.push('<span class="l-imagegrid-checkbox"></span>');
				arr.push('</div>');
			}
			var title = "";
			if(typeof(p.itemTitle) == "function"){
				title = p.itemTitle.call(g, d);
			}else if(p.itemTitle){
				title = g._getValueByName(d, p.itemTitle);
			}
			arr.push('<div class="l-imagegrid-title">'+title+'</div>');
			
			arr.push('</div>');//3
			
			if(p.itemState === true || p.itemState === 'true'){
				var left = p.spaceMargin + p.imgWidth - p.itemStateWidth;
				var top = p.spaceMargin + p.imgHeight - p.itemStateHeight;
				if(p.itemStatePos === 'RightBottom'){
				}else if(p.itemStatePos === 'LeftTop'){
					left = p.spaceMargin;
					top = p.spaceMargin;
				}else if(p.itemStatePos === 'RightTop'){
					left = p.spaceMargin + p.imgWidth - p.itemStateWidth;
					top = p.spaceMargin;
				}else if(p.itemStatePos === 'LeftBottom'){
					left = p.spaceMargin;
					top = p.spaceMargin + p.imgHeight - p.itemStateHeight;
				}
				var stateImg = p.itemStateImg;
				if(typeof(p.itemStateImg) == "function")
				{
					stateImg = p.itemStateImg.call(g, d);
				}
				if(stateImg.indexOf('#')!=-1){
					stateImg = g._getIconUrl(d, stateImg);
				}
				arr.push('<div class="l-imagegrid-state" style="top:'+top+'px;left:'+left+'px;width:'+p.itemStateWidth+'px;height:'+p.itemStateHeight+'px;">');
				arr.push(stateImg);
				arr.push('</div>');
			}
			arr.push('</div>');//1
			
			return arr.join('');
		},
		
		_getOperItemHtml: function(){
			var g = this, p = this.options;
			var arr = [];
			arr.push('<div id="'+p.operItemId+'" class="l-imagegrid-item">');
			//图片
			arr.push('<div class="l-imagegrid-img-wrap" style="margin:'+p.spaceMargin+'px;">');//2
			arr.push('<img class="l-imagegrid-img" style="width:'+p.imgWidth+'px; height:'+p.imgHeight+'px;"');
			arr.push(' src="'+p.operItem.icon+'"');
			
			var tit = p.operItem.name || p.operItem.title || '';
			arr.push(' alt="'+tit+'" title="'+tit+'"');
			arr.push('/>');
			
			arr.push('</div>');//2
			
			arr.push('</div>');//1
			
			return arr.join('');
		},
		_dynamicColumns: function ()
        {
        	var g = this, p = this.options;
        	g.dynamicHeader = null;
        	if(!g.currentData)return;
        	if(!g.currentData[p.dynamicHeader])return;
        	g.dynamicHeader = g.currentData[p.dynamicHeader];
        },
        _showData: function ()
        {
            var g = this, p = this.options;
            g._dynamicColumns();
            var data = g.currentData[p.root];
            if (p.usePager)
            {
                //更新总记录数
            	if (p.dataPageAction == 'server')
            		p.total = g.currentData[p.record];
            	else if (p.dataAction == "server" && g.data && g.data[p.record]){
                    p.total = g.data[p.record];
				}else if (g.filteredData && g.filteredData[p.root]){
                    p.total = g.filteredData[p.root].length;
				}else if (g.data && g.data[p.root]){
                    p.total = g.data[p.root].length;
				}else if (data){
                    p.total = data.length;
				}
                p.page = p.newPage;
                if (!p.total) p.total = 0;
                if (!p.page) p.page = 1;
                p.pageCount = Math.ceil(p.total / p.pageSize);
                if (!p.pageCount) p.pageCount = 1;
                //更新分页
                g._buildPager();
            }
            //加载中
            $('.l-bar-btnloading:first', g.toolbar).removeClass('l-bar-btnloading');
            if (g.trigger('beforeShowData', [g.currentData]) == false) return;
            g._clearGrid();
            if (!data) return;
            $(".l-bar-btnload:first span", g.toolbar).removeClass("l-disabled");
            g._updateGridData();
            g._fillGridBody(g.items);
            g.trigger('SysGridHeightChanged');
            if (p.mouseoverItemCssClass)
            {
            	$('.l-imagegrid-item', g._gridBodyInner).hover(function (){
            		$(this).addClass(p.mouseoverItemCssClass);
				}, function (){
					$(this).removeClass(p.mouseoverItemCssClass);
				});
            }
            g.gridbody.trigger('scroll.imagegrid');
            g.trigger('afterShowData', [g.currentData]);
            
            //滚动条
            if(p.niceScroll && p.niceScroll.enable && $.fn.niceScroll){
            	if(g.niceScrollObj){
            		g.niceScrollObj.remove();
            	}
				g.niceScrollObj = g.gridbody.niceScroll(g._gridBodyInner, p.niceScroll);
				g.niceScrollObj.onResize();
				
				g.gridbody.unbind('focus.niceScroll').bind('focus.niceScroll', function(){g.gridbody.blur();});
			}
            
            g._dynamicToolbar();
        },
        
        _getCurrentPageData: function (source)
        {
            var g = this, p = this.options;
            
            if(p.dataPageAction=='server'){
            	return source;
            }
            
            var data = {};
            data[p.root] = [];
            if (!source || !source[p.root] || !source[p.root].length)
            {
                data[p.record] = 0;
                return data;
            }
            data[p.record] = source[p.root].length;
            if (!p.newPage) p.newPage = 1;
            for (i = (p.newPage - 1) * p.pageSize; i < source[p.root].length && i < p.newPage * p.pageSize; i++)
            {
                data[p.root].push(source[p.root][i]);
            }
            return data;
        },
		_buildPager: function ()
        {
            var g = this, p = this.options;
            if(g.pagesizeSelector && p.pageSize != g.pagesizeSelector.val()){
            	var selectedIndex = -1;
                $(p.pageSizeOptions).each(function (i, item){
    				if (p.pageSize == item){
    					selectedIndex = i;
    				}
    			});
                if(selectedIndex != -1){
					g.pagesizeSelector[0].selectedIndex = selectedIndex;
				}
            }
            
            if(p.simplePage){
            	$(".l-bar-btnfirst,.l-bar-btnlast", g.toolbar).hide();
            	$('.pcontrol', g.toolbar).hide();
            	if (!p.total){
            		$(".l-bar-btnprev span,.l-bar-btnnext span", g.toolbar).addClass("l-disabled");
            	}
            	if(p.total==0){
            		$(".l-bar-btnprev span", g.toolbar).addClass("l-disabled");
            		$(".l-bar-btnnext span", g.toolbar).addClass("l-disabled");
            	}
            	if(p.total==-1){
            		$(".l-bar-btnnext span", g.toolbar).addClass("l-disabled");
            	}
            	if (p.page == 1){
            		$(".l-bar-btnprev span", g.toolbar).addClass("l-disabled");
            	}
            }else{
            	$('.pcontrol input', g.toolbar).val(p.page);
                if (!p.pageCount) p.pageCount = 1;
                $('.pcontrol span', g.toolbar).html(p.pageCount);
                var r1 = parseInt((p.page - 1) * p.pageSize) + 1.0;
                var r2 = parseInt(r1) + parseInt(p.pageSize) - 1;
                if (!p.total) p.total = 0;
                if (p.total < r2) r2 = p.total;
                if (!p.total) r1 = r2 = 0;
                if (r1 < 0) r1 = 0;
                if (r2 < 0) r2 = 0;
                if(p.hideStatMessage!==true){
                	var stat = p.pageStatMessage;
                    stat = stat.replace(/{from}/, r1);
                    stat = stat.replace(/{to}/, r2);
                    stat = stat.replace(/{total}/, p.total);
                    stat = stat.replace(/{pagesize}/, p.pageSize);
                    $('.l-bar-text', g.toolbar).html(stat);
                }else{
                	$('.l-bar-text', g.toolbar).html('');
                }
                
                if (!p.total)
                {
                    $(".l-bar-btnfirst span,.l-bar-btnprev span,.l-bar-btnnext span,.l-bar-btnlast span", g.toolbar).addClass("l-disabled");
                }
                if (p.page == 1)
                {
                    $(".l-bar-btnfirst span", g.toolbar).addClass("l-disabled");
                    $(".l-bar-btnprev span", g.toolbar).addClass("l-disabled");
                }
                else if (p.page > p.pageCount && p.pageCount > 0)
                {
                    $(".l-bar-btnfirst span", g.toolbar).removeClass("l-disabled");
                    $(".l-bar-btnprev span", g.toolbar).removeClass("l-disabled");
                }
                if (p.page == p.pageCount)
                {
                    $(".l-bar-btnlast span", g.toolbar).addClass("l-disabled");
                    $(".l-bar-btnnext span", g.toolbar).addClass("l-disabled");
                }
                else if (p.page < p.pageCount && p.pageCount > 0)
                {
                    $(".l-bar-btnlast span", g.toolbar).removeClass("l-disabled");
                    $(".l-bar-btnnext span", g.toolbar).removeClass("l-disabled");
                }
            }
            
        },
		_getItemIdByDomId: function (domid)
        {
            var ids = domid.split('|');
            var itemid = ids[1];
            return itemid;
        },
        _getItemByDomId: function (domid)
        {
            return this.records[this._getItemIdByDomId(domid)];
        },
        _getSrcElementByEvent: function (e)
        {
            var g = this;
            var obj = (e.target || e.srcElement);
            var jobjs = $(obj).parents().add(obj);
            var fn = function (clazz)
            {
                for (var i = 0; i < jobjs.length; i++)
                {
                   if ($(jobjs[i]).hasClass(clazz)) return jobjs[i];
                }
                return null;
            };
            if (jobjs.index(this.element) == -1) return { out: true };
            var r = {
                grid: fn("l-panel"),
                gridbody: fn("l-grid-body"),
                toolbar: fn("l-panel-bar")
            };
            if (r.gridbody)
            {
				r.item = fn("l-imagegrid-item");
				r.image = fn("l-imagegrid-img");
                r.checkbox = fn("l-imagegrid-checkbox-wrap");
				r.title = fn("l-imagegrid-title");
				if(r.item) r.data = this._getItemByDomId(r.item.id);
            }
            if (r.toolbar)
            {
                r.first = fn("l-bar-btnfirst");
                r.last = fn("l-bar-btnlast");
                r.next = fn("l-bar-btnnext");
                r.prev = fn("l-bar-btnprev");
                r.load = fn("l-bar-btnload");
                r.checkall = fn("l-bar-checkall");
                r.checkalltext = fn("l-bar-checkall-text");
            }

            return r;
        },
        _setEvent: function ()
        {
            var g = this, p = this.options;
            $(document).bind("click.imagegrid_"+g.id, function (e)
            {
                g._onClick.call(g, e);
            });
            $(window).bind("resize.imagegrid_"+g.id, function (e)
            {
                g._onResize.call(g);
            });
            $(document).bind("keydown.imagegrid_"+g.id, function (e)
            {
                if (e.ctrlKey) g.ctrlKey = true;
            });
            $(document).bind("keyup.imagegrid_"+g.id, function (e)
            {
                delete g.ctrlKey;
            });
            //工具条 - 切换每页记录数事件
            $('select', g.toolbar).change(function ()
            {
                p.newPage = 1;
                p.pageSize = this.value;
                g.loadData();
            });
            //工具条 - 切换当前页事件
            $('span.pcontrol :text', g.toolbar).blur(function (e)
            {
                g.changePage('input');
            });
            $("div.l-bar-button", g.toolbar).hover(function ()
            {
                $(this).addClass("l-bar-button-over");
            }, function ()
            {
                $(this).removeClass("l-bar-button-over");
            });
            
        },
        _onItemOver: function (itemParm, over)
        {
            var g = this, p = this.options;
            var itemdata = g.getItem(itemParm);
            var methodName = over ? "addClass" : "removeClass";
            $(g.getItemObj(itemdata))[methodName](p.mouseoverItemCssClass);
        },
        _onClick: function (e)
        {
            var obj = (e.target || e.srcElement);
            var g = this, p = this.options;
            var src = g._getSrcElementByEvent(e);
            if(src.out || e.which>1)  return;
            if(src.gridbody && !src.item){
            	if(!g.enabledCheckbox() && g.selected.length>0){
            		for(var rowid in g.records)
            		{
            			var itemdata = g.getItem(rowid);
        				var itemobj = $(g.getItemObj(itemdata['__id']));
        				if(itemobj.hasClass("l-imagegrid-checked")){
        					g.unselect(rowid);
        				}
            		}
    			}
            }
            if(src.item && src.item.id==p.operItemId){
            	if(p.operItem.click){
            		p.operItem.click.call(g, p.operItem, src.item);
            	}
            }
            else if (src.checkbox && g.enabledCheckbox()) //复选框
            {
				var item = $(src.item);
				var uncheck = item.hasClass("l-imagegrid-checked");
				if (g.trigger('beforeCheck', [!uncheck, src.data, src.data['__id'], src.item]) == false){
                    return false;
				}
				var met = uncheck ? 'unselect' : 'select';
				g[met](src.data);
				g.trigger('check', [!uncheck, src.data, src.data['__id'], src.item]);
				g._dynamicToolbar();
            }
			else if(src.image){
				if(p.onClickImage){
					g.trigger('clickImage', [src.data, src.item]);
				}else if(src.item){
					var item = $(src.item);
					var uncheck = item.hasClass("l-imagegrid-checked");
					if (g.trigger('beforeCheck', [!uncheck, src.data, src.data['__id'], src.item]) == false){
	                    return false;
					}
					var met = uncheck ? 'unselect' : 'select';
					g[met](src.data);
					g.trigger('check', [!uncheck, src.data, src.data['__id'], src.item]);
					g._dynamicToolbar();
				}
			}
			else if(src.title){
				if(p.onClickTitle){
					g.trigger('clickTitle', [src.data, src.item]);
				}else if(src.item){
					var item = $(src.item);
					var uncheck = item.hasClass("l-imagegrid-checked");
					if (g.trigger('beforeCheck', [!uncheck, src.data, src.data['__id'], src.item]) == false){
	                    return false;
					}
					var met = uncheck ? 'unselect' : 'select';
					g[met](src.data);
					g.trigger('check', [!uncheck, src.data, src.data['__id'], src.item]);
					g._dynamicToolbar();
				}
			}
            else if (src.toolbar)
            {
                if (src.first)
                {
                    if (g.trigger('toFirst', [g.element]) == false) return false;
                    g.changePage('first');
                }
                else if (src.prev)
                {
                    if (g.trigger('toPrev', [g.element]) == false) return false;
                    g.changePage('prev');
                }
                else if (src.next)
                {
                    if (g.trigger('toNext', [g.element]) == false) return false;
                    g.changePage('next');
                }
                else if (src.last)
                {
                    if (g.trigger('toLast', [g.element]) == false) return false;
                    g.changePage('last');
                }
                else if (src.load)
                {
                    if ($("span", src.load).hasClass("l-disabled")) return false;
                    if (g.trigger('reload', [g.element]) == false) return false;
                    g.loadData();
                }
                else if (src.checkall || src.checkalltext)
                {
                	var chkAll = g.checkall;
                    var uncheck = chkAll.hasClass("l-checked");
                    if (g.trigger('beforeCheckAll', [!uncheck, g.element]) == false) return false;
                    if (uncheck)
                    {
                    	chkAll.removeClass("l-checked");
                    	g._unselectAll_inner();
                    }
                    else
                    {
                    	chkAll.addClass("l-checked");
                    	g._selectAll_inner();
                    }
                    g.trigger('checkAll', [true, g.element]);
        			g._dynamicToolbar();
                }
            }
        },
        
        selectByDataIds: function(ids, idfield, dynamicToolbar)
        {
        	var g = this, p = this.options;
        	var map = {};
        	for(var i in ids){
        		map['_'+ids[i]] = true;
        	}
        	for(var i in g.records){
        		var itm = g.records[i];
        		if(map['_'+itm[idfield]]){
        			g.select(itm, true);
        		}else{
        			g.unselect(itm, true);
        		}
        	}
        	dynamicToolbar && g._dynamicToolbar();
        },
        
        
		select: function (itemParm, trigger, dynamicToolbar)
		{
			var g = this, p = this.options;
			if(!g.enabledCheckbox() && !g.ctrlKey){
				g._unselectAll_inner();
			}
			var itemdata = g.getItem(itemParm);
			var itemid = itemdata['__id'];
			var itemobj = g.getItemObj(itemid);
			
			if (trigger && g.trigger('beforeCheck', [true, itemdata, itemid, itemobj]) == false){
                return false;
			}
			
			if (itemobj && !$(itemobj).hasClass('l-imagegrid-checked')) $(itemobj).addClass("l-imagegrid-checked");
			g.selected[g.selected.length] = itemdata;
			
			if (trigger) g.trigger('check', [true, itemdata, itemid, itemobj]);
			if (dynamicToolbar) g._dynamicToolbar();
		},
		unselect: function (itemParm, trigger, dynamicToolbar)
		{
			var g = this, p = this.options;
			var itemdata = g.getItem(itemParm);
			var itemid = itemdata['__id'];
			var itemobj = g.getItemObj(itemid);
			
			if (trigger && g.trigger('beforeCheck', [false, itemdata, itemid, itemobj]) == false){
                return false;
			}
			
			$(itemobj).removeClass("l-imagegrid-checked");
			var index = $.inArray(itemdata, g.selected);
            if (index != -1) g.selected.splice(index, 1);
            
            if (trigger) g.trigger('check', [false, itemdata, itemid, itemobj]);
            if (dynamicToolbar) g._dynamicToolbar();
		},
		isSelected: function (itemParm)
        {
            var g = this, p = this.options;
            var itemdata = g.getItem(itemParm);
            for (var i in g.selected)
            {
                if (g.selected[i] == rowdata) return true;
            }
            return false;
        },
		selectAll: function()
		{
			var g = this, p = this.options;
			if(!g.enabledCheckbox()){
				return;
			}
			if(g.trigger('beforeCheckAll', [true, g.element]) == false) return false;
			g.checkall.addClass("l-checked");
			g._selectAll_inner();
			g.trigger('checkAll', [true, g.element]);
			g._dynamicToolbar();
		},
		_selectAll_inner: function()
		{
			var g = this, p = this.options;
			g.selected = [];
			for(var rowid in g.records)
			{
				var itemdata = g.getItem(rowid);
				var itemobj = $(g.getItemObj(itemdata['__id']));
				if(!itemobj.hasClass("l-imagegrid-checked")){
					itemobj.addClass("l-imagegrid-checked");
				}
				g.selected[g.selected.length] = itemdata;
			}
		},
		unselectAll: function()
		{
			var g = this, p = this.options;
			if(g.trigger('beforeCheckAll', [false, g.element]) == false) return false;
			g.checkall.removeClass("l-checked");
			g._unselectAll_inner();
			g.trigger('checkAll', [false, g.element]);
			g._dynamicToolbar();
		},
		_unselectAll_inner: function()
		{
			var g = this, p = this.options;
			g.selected = [];
			for(var rowid in g.records)
			{
				var itemobj = $(g.getItemObj(rowid));
				itemobj.removeClass("l-imagegrid-checked");
			}
		},
        _onResize: function ()
        {
            var g = this, p = this.options;
            if (p.height && p.height != 'auto')
            {
                var windowHeight = $(window).height();
                var h = 0;
                var parentHeight = null;
                if (typeof (p.height) == "string" && p.height.indexOf('%') > 0)
                {
                    var gridparent = g.grid.parent();
                    if (p.inWindow)
                    {
                        parentHeight = windowHeight;
                        parentHeight -= parseInt($('body').css('paddingTop'));
                        parentHeight -= parseInt($('body').css('paddingBottom'));
                    }
                    else
                    {
                        parentHeight = gridparent.height();
                    }
                    h = parentHeight * parseFloat(p.height) * 0.01;
                    if (p.inWindow || gridparent[0].tagName.toLowerCase() == "body"){
                        h -= (g.grid.offset().top - parseInt($('body').css('paddingTop')));
					}
                }
                else
                {
                    h = parseInt(p.height);
                }
                g.windowHeight = windowHeight;
                g._setHeight(h);
            }
            if(g.niceScrollObj){
            	g.niceScrollObj.onResize();
            }
            g.trigger('SysGridHeightChanged');
        },
        _dynamicToolbar: function(){
			var g = this, p = this.options;
			if(!p.dynamicToolbar)return;
			var items = g.getSelectedItems();
			if(p.dynamicToolbarRender){
				var b = p.dynamicToolbarRender.call(g, items.length, items);
				if(b!==true)return;
			}
			if(!g.toolbarManager)return;
			g.toolbarManager.setDisplay(items.length);
		},
		_getIconUrl: function(record, iconurl)
		{
			var _text = iconurl.replace(/#\{(.+?)}/g, function(word, key){
        		if(key.indexOf('.') == -1){
        			if(record[key]===0 || record[key]===false || record[key]===''){
        				return record[key];
        			}
        			return !!record[key] ? record[key] : word;
				}else{
					try{
						var txt = new Function("record", "return record."+key+";")(record);
						if(txt===0 || txt===false || txt===''){
	        				return txt;
	        			}
						return txt || word;
					}catch(e){
						return word;
					}
				}
			});
        	return _text;
		},
		getDataList: function(){
			return this.items;
		},
		destroy: function ()
        {
			var g = this;
			g._destroyed = true;
			$(document).unbind("click.imagegrid_"+g.id);
            $(window).unbind("resize.imagegrid_"+g.id);
            $(document).unbind("keydown.imagegrid_"+g.id);
            $(document).unbind("keyup.imagegrid_"+g.id);
            $.ligerui.remove(g);
			g.grid.empty();
			delete g.options;
        }
    });
    $.ligerui.controls.ImageGrid.prototype.setOptions = $.ligerui.controls.ImageGrid.prototype.set;
    $.ligerui.controls.ImageGrid.prototype.getSelecteds = $.ligerui.controls.ImageGrid.prototype.getSelectedItems;
})(jQuery);
